package com.ruoyi.app.common.utils;


import com.ruoyi.common.exception.BusinessException;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Map;

public class ImageUtils {
    private static String staticPath;

    static {
        String dir = System.getProperty("user.dir");
        if (System.getProperty("os.name").startsWith("Win") || System.getProperty("os.name").startsWith("win")) {
            staticPath = dir + "/ruoyi-app/src/main/resources/static/";
        } else {
            staticPath = new File(dir).getParent() + "/ruoyi-app/src/main/resources/static/";
        }
    }

    public static InputStream posterCompose(Map<String, String> posterUrls) {
        try {
            Thumbnails.Builder builder = Thumbnails.of(new File(staticPath + posterUrls.get("bg"))).scale(1).outputQuality(1f);
            BufferedImage wxaCodeImgBuffer = ImageIO.read(new URL(posterUrls.get("qr_code_url")));
            builder.watermark(PosterPosition.QRCODE, wxaCodeImgBuffer, 1f);
            if (posterUrls.containsKey("savePath")) {
                builder.toFile(posterUrls.get("savePath"));
                return null;
            } else {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(builder.asBufferedImage(), "png", os);
                return new ByteArrayInputStream(os.toByteArray());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new BusinessException("合成海报失败！");
    }


    private enum PosterPosition implements net.coobird.thumbnailator.geometry.Position {
        QRCODE {
            public Point calculate(int var1, int var2, int var3, int var4, int var5, int var6, int var7, int var8) {
                int x = 150;
                int y = 615;
                return new Point(x, y);
            }
        }
    }
}
